<?php

namespace App\Services\Admin\User;

use Exception;

class UserService extends BaseUserService
{

    /**
     * 用户列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        // 查询用户列表总条数
        $total = $this->getUserModel()->total($params);
        // 查询用户列表
        $userList = $this->getUserModel()->list($params, [
            'id', 'nickname', 'invite_user_id', 'phone', 'integral', 'created_at'
        ]);

        // 获取用户ids
        $userIds = array_column($userList, 'id');

        // 获取邀请用户ids
        $inviteUserIds = array_unique(array_column($userList, 'invite_user_id'));

        // 查询邀请用户列表
        $inviteUserList = $this->getUserModel()->getItemsByIds($inviteUserIds, [
            'id', 'phone'
        ]);
        $inviteUserListMap = array_column($inviteUserList, null, 'id');

        // 查询被邀请人数量
        $invitedUserList = $this->getUserModel()->getGroupTotalByInviteUserId($userIds);
        $invitedUserTotalMap = array_column($invitedUserList, 'count', 'invite_user_id');

        // 整理数据格式
        $list = [];
        foreach ($userList as $item) {
            $list[] = [
                'id' => $item['id'],
                'nickname' => $item['nickname'],
                'phone' => $item['phone'],
                'invitePhone' => $inviteUserListMap[$item['invite_user_id']]['phone'] ?? '',
                'integral' => $item['integral'],
                'inviteTotal' => $invitedUserTotalMap[$item['id']] ?? 0,
                'createdAt' => $item['created_at']
            ];
        }

        return [
            'list' => $list,
            'total' => $total,
        ];
    }

    /**
     * 邀请用户列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function inviteList(array $params): array
    {
        // 总人数
        $total = $this->getUserModel()->getTotalByInviteUserId($params['userId']);

        // 邀请用户列表
        $userList = $this->getUserModel()->getItemByInviteUserId($params['userId'], [
            'id', 'nickname', 'phone', 'integral', 'created_at'
        ]);

        $list = [];
        foreach ($userList as $item) {
            $list[] = [
                'id' => $item['id'],
                'nickname' => $item['nickname'],
                'phone' => $item['phone'],
                'integral' => $item['integral'],
                'createdAt' => $item['created_at']
            ];
        }

        return [
            'list' => $list,
            'total' => $total,
        ];
    }
}
